//
//  OffRecordViewController.m
//  iHealthEHR
//
//  Created by Joseph Ayo Akinyele on 6/4/10.
//  Copyright 2010 Johns Hopkins University. All rights reserved.
//

#import "OffRecordViewController.h"


@implementation OffRecordViewController
@synthesize ccrSections, ccrCategoryKey;
@synthesize ccrEntries;

#pragma mark -
#pragma mark Initialization

- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if ((self = [super initWithStyle:style])) {
		ccrSections = [[NSArray alloc] initWithObjects:@"Conditions", @"Medications",
					   @"Allergies", @"Procedures", @"Test Results", @"Immunizations", @"Insurance", nil];
		ccrCategoryKey = [[NSArray alloc] initWithObjects:@"CONDITION", @"MEDICATION",
						  @"ALLERGY", @"PROCEDURE", @"LABTEST", @"IMMUNIZATION", @"PAYER", nil];
		ccrImageKey = [[NSArray alloc] initWithObjects:@"StethoBleu-64.png", @"Pills-64.png", 
					   @"Genetics-64.png", @"Case-64.png", @"Caducee-64.png", @"Seringue-64.png", @"HealthShield-64.png", nil];
		ccrCacheImage = [[NSMutableArray alloc] init];
		for(int i = 0; i < [ccrImageKey count]; i++) {
			UIImage *image = [UIImage imageNamed:[ccrImageKey objectAtIndex:i]];
			[ccrCacheImage insertObject:image atIndex:i];
		}				
    }
    return self;
}

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
	[self.navigationController setToolbarHidden:NO];	
	//create two buttons, add them to an array and load them in the toolbar
	UIBarButtonItem *newButton = [[UIBarButtonItem alloc] initWithTitle:@"Offline Info" style:UIBarButtonItemStyleBordered target:self action:@selector(loadinfo)];
		
	NSArray *buttons = [[NSArray alloc] initWithObjects:newButton, nil];
	// each view controller has its own toolbar that can be set appropriately.
	[self setToolbarItems:buttons];
	[newButton release];
	[buttons release];	
	
    [super viewDidLoad];

	if(cpabe == nil) {
		cpabe = [[CPABEInterface alloc] init];
		[cpabe Initialize];
		[cpabe ReadParameters];
		
		/* temporary */
		[cpabe RetrieveKey:nil with:nil];
		
		if(detailedView == nil) {
			detailedView = [[DetailedViewController alloc] initWithNibName:nil bundle:nil];
			detailedView.ptrToCPabe = cpabe;
		}		
	}	
	
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Logout" style:UIBarButtonItemStylePlain 
																			  target:self action:@selector(logout)] autorelease];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewWillAppear:(BOOL)animated {
	[self.navigationController setToolbarHidden:NO];
    [super viewWillAppear:animated];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [ccrSections count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *ProfileCellIdentifier = @"ProfileCellIdentifier";
    
    ProfileCell *cell = (ProfileCell *)[tableView dequeueReusableCellWithIdentifier:ProfileCellIdentifier];
    if (cell == nil) {
		// load nib life
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ProfileCell" 
													 owner:self 
												   options:nil];
		// retrieve cell object in nib file.
		cell = [nib objectAtIndex:0];
    }
    
    // Configure the cell...
	NSUInteger row = [indexPath row];
	cell.section.text = [ccrSections objectAtIndex:row];
	// get number of entires in this specific CCR category
	cell.item.text = [self getItemCount:[ccrCategoryKey objectAtIndex:row]];
	cell.imageView.image = [ccrCacheImage objectAtIndex:row];	
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	NSUInteger row = [indexPath row];
	NSString *selSection = [ccrCategoryKey objectAtIndex:row];	
	NSArray *entries = [self getEntryByCategory:selSection];
	
	if([entries count] > 0) {
		SEL myOptions = @selector(myCCROptionsOff);
		detailedView.ccrObjects = entries;
		detailedView.title = [ccrSections objectAtIndex:[indexPath row]];
		detailedView.ccrSubSection = selSection; // may need to pass on to WebView?
		detailedView.LoggedInThruGoogleHealth = YES;
		detailedView.selTarget = self;
		detailedView.selFunction = myOptions;
		[self.navigationController pushViewController:detailedView animated:YES];		
	}
	[entries release];
}


#pragma mark -
#pragma mark Memory management

- (void) didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void) viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[ccrSections release];
	[ccrCategoryKey release];
	[ccrEntries release];
	[ccrImageKey release];
    [super dealloc];
}

#pragma mark -
#pragma mark Utility functions

-(void) logout
{
	NSLog(@"Are you sure?");
	[self.navigationController popToRootViewControllerAnimated:YES];
}

-(NSString *) getItemCount:(NSString *)section
{
	// in case entries arent set.	
	CCRObject *entry;
	
	int maxCount = [ccrEntries count];
	int itemCount = 0;
	for(int i = 0; i < maxCount; i++) {
		// Retrieve each profile 
		entry = [ccrEntries objectAtIndex:i];
		NSString *ccrTerm = [entry ccrsection];
		if([ccrTerm isEqualToString:section]) {
			itemCount++;
		}		
	}
	
	return [NSString stringWithFormat:@"%d items", itemCount];
}

-(NSArray *) getEntryByCategory:(NSString *)section
{
	CCRObject *entry;
	int max = [ccrEntries count];
	NSMutableArray *_array = [[NSMutableArray alloc] init];
	for(int i = 0; i < max; i++) {
		entry = [ccrEntries objectAtIndex:i];
		if([entry.ccrsection isEqualToString:section])
			[_array addObject:entry];
	}
	
	if([_array count] > 0) {
		return _array;
	}
	
	[_array release];
	return nil;
}

-(void) loadinfo
{
	// if mvc is active ViewController, then do nothing!
	NSString *title = @"About Us";
	
	if(info == nil) {
		info = [[MedsViewController alloc] initWithNibName:@"MedsViewController" bundle:nil];
	}	
	info.title = title;
	info.curCategory = @"offline";
	[self.navigationController pushViewController:info animated:YES];
}

-(void) myCCROptionsOff
{
	/* Support decryption (IMPLEMENT NEXT), upload to GH (DONE), and edit policy (FUTURE WORK) */
	UIActionSheet *menu = [[UIActionSheet alloc]
						   initWithTitle:@"Options" 
						   delegate:self 
						   cancelButtonTitle:@"Cancel" 
						   destructiveButtonTitle:nil 
						   otherButtonTitles:@"Decrypt All", nil];
	[menu showInView:detailedView.view];
}

-(void) actionSheet:(UIActionSheet *) actionSheet clickedButtonAtIndex:(NSInteger) buttonIndex
{
	if(buttonIndex == 0) { /* DECRYPT OPTION */
		NSString *status = [[NSString alloc] initWithFormat:@"Decrypting %@ section...", detailedView.ccrSubSection]; 
		[detailedView showTheProgress:status];
		[status release];
		BOOL _decrypt = NO;
		// means we decrypt for Google Health (only the currently viewed section)
		NSArray *entries = detailedView.ccrObjects;
		for(int i = 0; i < [entries count]; i++) {
			CCRObject *c = [entries objectAtIndex:i];
			if([c decryptElementFromGoogleHealth:cpabe] == YES) {
				NSString *text = [DetailedViewController parseDescription:c ofCCR:detailedView.ccrSubSection];
				c.item = text;
				// NSLog(@"New text = %@", text);
				_decrypt = YES;
				detailedView.UserSelectedDecryption = YES;
				// detailedView.ptrToCPabe = cpabe;
			}
		}
		
		if(!_decrypt) {
			[CCRObject popUpNotice:@"Decrypt" withMessage:@"Nothing to decrypt."];	
		}
		
	}
	else {
		NSLog(@"Cancel");
	}
	
	[detailedView.tableView reloadData];
	[actionSheet release];
}

@end

